<template>
    <div class="whitebg logincontainer">
        <!-- <van-nav-bar fixed :title="routerName=='Useredit'?'个人信息':'完善个人信息'" left-arrow @click-left='goBack'></van-nav-bar> -->
        <div class="loginwarpper flexcenter flexcolumn">
            <div class="reg_title">{{routerName=='Useredit'?'查看个人信息':'完善个人信息'}}</div>
            <!-- <div class="logintop">
                <img src="@/assets/images/loginbg.png" alt="" srcset="">
            </div> -->
            <div class="loginbox">
                <van-form class="loginboxform"  @submit="onSubmit">
                    <van-field v-model="form.name" label="" :rules="[{ required: true, message: '请输入姓名' }]" class="mb_12" placeholder="请输入姓名" />
                    <van-field v-model="typename" name="picker" label="" :rules="[{ required: true, message: '请选择支付方式' }]" placeholder="请选择支付方式" class="mb_12" @click="showPicker = true"  />
                    <van-popup v-model="showPicker" position="bottom">
                        <van-picker show-toolbar :columns="columns" value-key="value" @confirm="onConfirm" @cancel="showPicker = false" />
                    </van-popup>
                    <van-field v-model="form.phone" label="" :rules="[{ required: true, message: '请输入联系方式' }]" class="mb_12" placeholder="请输入联系方式" />
                    <van-field v-if="typename=='支付宝'" v-model="form.account" label="" :rules="[{ required: true, message: '支付账号' }]" class="mb_12 " placeholder="请输入支付宝账号" />
                    <van-field v-if="typename=='微信'" name="uploader" label="" class="fileformitem">
                        <template #input>
                            <div class="uploadflexend">
                                <van-uploader 
                                    v-model="fileList" 
                                    :max-count='1' 
                                    @oversize="onOversize" 
                                    :before-read='beforeRead'
                                    :after-read="afterRead" 
                                    :max-size="5 * 1024 * 1024"	/>
                                    <span>请上传微信收款二维码</span>
                            </div>
                        </template>
                    </van-field>
                    <!-- :rules="[{pattern:/^.{6,18}$/, message:'密码长度必须为6-18个字符'}]"  -->
                    <van-field 
                        v-if="routerName=='Useredit'"
                        v-model="form.pass" 
                        :type="showpsd1?'':'password'" 
                        label="" 
                        :right-icon="showpsd1?'eye-o':'closed-eye'"
                        class="mb_12" 
                        placeholder="请输入新密码"
                        @click-right-icon="showPassword(1)" />
                    <template v-if="routerName=='Useredit'">
                        <van-button class="loadbtn" native-type="submit">
                        <!-- <div class="mt-80 loadbtn" @click="onSubmit"> -->
                            <van-loading v-if='loading' type="spinner" size="16px" color="#fff"/> 
                            <span class="logintext"> 修改信息 </span>
                        </van-button>
                        <div class="mt-80 loadbtn canclebtn" @click="onLoginout">
                            <span class=""> 退出登录 </span>
                        </div>
                    </template>
                    <template v-else>
                        <div class="mt-80 loadbtn" @click="onSubmit">
                            <van-loading v-if='loading' type="spinner" size="16px" color="#fff"/> 
                            <span class="logintext"> 保 存 </span>
                        </div>
                        <div class="flexcenter bottomspan">
                            <span class="commhover" @click="goPage('login')">已有账户，立即登陆</span>
                        </div>
                    </template>
                </van-form>
            </div>
        </div>
    </div>
</template>

<script>
import MyPicker from "@/components/MyPicker.vue";
import { Toast } from 'vant'
import { mapState } from 'vuex';
import { uploadFiles } from '@/api/comm';
import Cookies from 'js-cookie';
import { removeToken } from '@/utils/auth'

export default {
  data() {
    return {
      routerName:'',
      loading:false,
      showpsd1:false,
      form:{
        name:"",
        phone:'',
        account:"",
        type:1,
        pass:''
      },
      typename:'',
      showPicker:false,
      columns:[{value:'微信',id:2},{value:'支付宝',id:1}],
      fileList:[],//上传图片
    }
  },

  components:{
    MyPicker
  },

  created(){
    console.log('router:',this.$route);
    console.log('user:',this.user);
    this.routerName = this.$route.name;
    if(this.$route.name =='Useredit'){
        this.form.name = this.user.name;
        this.form.account = this.user.account;
        this.form.type = this.user.pay_type;
        this.form.phone = this.user.phone;
        if(this.user.pay_type==1){
            this.typename='支付宝'
        }else{
            this.typename = '微信';
            this.fileList=[{url:this.user.url,isImage: true}]
        }
        // this.form.pass=Cookies.get('password');
    }   
  },

  computed:{
    ...mapState({
        user:state => state.user.user
    })
  },

  mounted() {

  },

  methods: {

    goBack(){
        this.$router.back();
    },

    onConfirm(val,index){
        this.typename = val.value;
        this.showPicker = false;
        console.log('val:',val,index);        
    },

    onOversize(file) {
      this.$toast("文件大小不能超过5MB");
    },
    //校验图片的格式
    beforeRead(file) {
      if (!/(jpg|jpeg|png|JPG|PNG)/i.test(file.type)) {
        this.$toast("请上传正确格式的图片");
        return false;
      }
      return true;
    },

    afterRead(file){
        // 上传状态提示开启
      file.status = "uploading";
      file.message = "上传中...";
      // 创建一个空对象实例
      let formData = new FormData();
      // 调用append()方法添加数据
      formData.append("photo", file.file);
      uploadFiles(formData).then((res) => {
        if (res.code == 1) {
          // 上传状态提示关闭
          file.status = "done";
          this.$toast("上传成功！");
          this.clzpfilePath = res.data.relativePath; //删除所需参数
          console.log('this.fileList:',this.fileList);
          let url = res.data.replace('\\','/');
        //   this.form.photo = process.env.VUE_APP_BASE_API+'/'+url;
          this.fileList[0].url = process.env.VUE_APP_BASE_API+'/'+url;
          console.log('this.fileList:',this.fileList);
        }
      });
    },

    //照片删除事件方法
    deleteClzp() {
      // filePath：删除所需的参数
      deleteFiles({ filePath: this.clzpfilePath }).then((res) => {
        if (res.code == "10000") {
          this.$toast("删除成功！");
        }
      });
    },

    showPassword(){
        this.showpsd1 = !this.showpsd1
    },

    async goPage(page){
        await this.$store.dispatch('user/logout');
        location.reload();
        // this.$router.push({path:page})
    },

    onSubmit(){
        let params = {
            name:this.form.name,
            phone:this.form.phone,
            type:this.typename=='微信'?2:1
        }
        if(params.type == 2){//微信
            if(!this.fileList.length){
                this.$toast('请上传二维码');
                return 
            }
            params.account = this.fileList[0].url;
        }else{
            params.account = this.form.account;
        }
        console.log('params：',params);
        if(this.form.pass){
            if(!/^.{6,18}$/.test(this.form.pass)){
                this.$toast('密码长度必须为6-18个字符');
                return;
            }
            params.password = this.form.pass;
        }
        this.loading = true;
        this.$store.dispatch('user/editUserInfo',params).then(()=>{
            this.$toast('修改成功');
            if(this.routerName == 'userinfo'){
                this.$router.push({ path: "/bootpage" })
            }else{
                this.form.pass=''
                // Cookies.set('password',this.form.pass);
            }
            this.loading = false;
        }).catch(e=>{
            this.loading = false;
        })
    },


    // 退出登录
    onLoginout(){
        this.$dialog.confirm({
            title: '提示',
            message: '确定注销并退出系统吗？',
        }).then(async () => {
            await this.$store.dispatch('user/logout');
            location.reload();
        })
        .catch(() => {
            // on cancel
            console.log('取消')
        });
    },
  }
}
</script>
<style lang="scss">
.loginboxform{
    .van-cell{
        padding: 0;
        background-color: transparent;
    }
    .van-field__body{
        background-color: white;
        padding: 20px 32px;
        border-radius: 12px;
        border: 1px solid #eee;
    }
    .van-field__control{
        // border: 1px solid #000;
    }
    .van-cell::after{
        border: 0;
    }
    .van-field__error-message{
        padding-left:32px;
    }
    .fileformitem{
        .van-field__body{
            padding: 0;
            border: 0;
        }
    }
    .van-button::before{
        background-color:transparent;
        border: 0;
    }
}
</style>
<style lang="scss" scoped>
.logincontainer{
  width: 100%;
  height: 100vh;
  
}
.loginwarpper{
    width: 100%;
    height: 100%;
    background: url('~@/assets/images/registerbg.png') center no-repeat;
    background-size: 100% 100%;
}
.reg_title{
    font-size: 44px;
    color: #000;
}
.loginbox{
    width: 100%;
    padding: 0 40px 40px;
    margin-top: 68px;
}
.loadbtn{
    margin-top: 60px;
    width: 100%;
    height: 80px;
    background: url('~@/assets/images/lgoinbg.png') center no-repeat ;
    background-size: contain;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30px;
    border: 0;
}
.canclebtn{
    background:#fff;
    border: 1px solid #EC865C;
    border-radius: 50px;
    width: 92%;
    margin: auto;
    margin-top: 30px;
}
.logintext{
    margin-top: -10px;
}
.bottomspan{
    padding: 32px 36px 0;
    span{
        font-size: 28px;
    }
}
.uploadflexend{
    display: flex;
    align-items: flex-end;

    &>span{
        padding-bottom: 20px;
        color: #999;
    }
}
</style>
